<?php
declare (strict_types = 1);

namespace daayu\taskload\service;

use daayu\taskload\TaskLoadConfig;

/**
 * 计划任务服务器项目Service层
 */
class TaskServerProjectService extends BaseService
{
    protected $table = 'zn_task_server_project';

    public function list($args = [])
    {
        $page = isset($args['page']) ? intval($args['page']) : 1;
        $rows = isset($args['rows']) ? intval($args['rows']) : 20;
        $field = isset($args['field']) ? trim($args['field']) : 'id,server_id,project_id,project_path,create_time';
        $orderBy = isset($args['order_by']) ? $args['order_by'] : 'id desc';
        $where = [];
        if(isset($args['server_id']) && intval($args['server_id']) > 0){
            $where[] = ['server_id', '=', intval($args['server_id'])];
        }
        if(isset($args['project_id']) && intval($args['project_id']) != 0){
            $where[] = ['project_id', '=', intval($args['project_id'])];
        }
        $rs = $this->table()->where($where)->page($page, $rows)->field($field)->order($orderBy)->select()->toArray();
        if(!empty($rs)){
            $project_names = $this->table(TaskLoadConfig::TABLE_TASK_PROJECT)->column('name', 'id');
            foreach($rs as $k => &$v){
                if(isset($v['project_id'])) $v['project_name'] = $project_names[$v['project_id']] ?? '';
            }
        }
        $ret['total'] = isset($args['total']) ? $args['total'] : $this->table()->where($where)->count();
        $ret['page'] = $page;
        $ret['rows'] = $rs;
        return $ret;
    }

    public function get($id, $field=null)
    {
        $id = intval($id);
        if($id <= 0){
            $this->error = '参数错误';
            return false;
        }
        $info = $this->table()->where('id', $id)->field($field)->find();
        if(!$info){
            $this->error = '指定的记录不存在';
            return false;
        }
        return $info;
    }

    public function save($data = [])
    {
        $id = 0;
        if(isset($data['id'])){
            $id = intval($data['id']);
            unset($data['id']);
            if(empty($id) || $this->table()->where('id', $id)->value('id') == null){
                $this->error = '指定的记录不存在';
                return false;
            }
        }
        //验证数据
        if(isset($data['server_id'])){
            $data['server_id'] = intval($data['server_id']);
            if($data['server_id'] <= 0){
                $this->error = '未指定服务器';
                return false;
            }
        }
        if(isset($data['project_id'])){
            $data['project_id'] = intval($data['project_id']);
            if($data['project_id'] <= 0){
                $this->error = '未指定项目';
                return false;
            }
        }
        if(isset($data['project_path'])){
            $data['project_path'] = trim($data['project_path']);
            if(empty($data['project_path'])){
                $this->error = '项目路径不能为空';
                return false;
            }
            if(substr($data['project_path'], strlen($data['project_path'])-1, 1) != '/'){
                $data['project_path'] .= '/';
            }
        }
        if($id > 0){
            $r = $this->table()->where('id', $id)->update($data);
        }else{
            //检测是否重复
            $exist_id = $this->table()->where('server_id', $data['server_id'])->where('project_id', $data['project_id'])->value('id');
            if($exist_id){
                $this->error = '服务器已存在该项目，不可重复添加';
                return false;
            }
            $id = $this->table()->insertGetId($data);
        }
        return $id;
    }

    public function delete($args = []){
        $where = [];
        if(isset($args['id'])){
            $where[] = ['id', '=', $args['id']];
        }
        if(isset($args['server_id'])){
            $where[] = ['server_id', '=', $args['server_id']];
        }
        if(isset($args['project_id'])){
            $where[] = ['project_id', '=', $args['project_id']];
        }
        if(empty($where)){
            $this->error = '参数错误';
            return false;
        }
        $exist_rs = $this->table()->where($where)->field('server_id,project_id')->select()->toArray();
        if(empty($exist_rs)){
            $this->error = '记录不存在';
            return false;
        }
        $server_ids = [];
        $project_ids = [];
        foreach ($exist_rs as $k => $v) {
            $server_ids[] = $v['server_id'];
            $project_ids[] = $v['project_id'];
        }
        // 启动事务
        $this->db()->startTrans();
        try {
            $r = $this->table()->where($where)->delete();
            //删除相关
            $r = $this->table(TaskLoadConfig::TABLE_TASK_SERVER_RELATE)->where('server_id', 'in', $server_ids)->where('project_id', 'in', $project_ids)->delete();
            // 提交事务
            $this->db()->commit();
            return $r;
        } catch (\Exception $e) {
            // 回滚事务
            $this->db()->rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }

    public function createDb()
    {
        if(!$this->checkTable()){
            $sql = "CREATE TABLE `".$this->table."`  (
                `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
                `server_id` int(11) DEFAULT '0' COMMENT '服务器id',
                `project_id` int(11) DEFAULT '0' COMMENT '项目id',
                `project_path` varchar(255) DEFAULT '' COMMENT '项目路径',
                `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                PRIMARY KEY (`id`)
              ) ENGINE = InnoDB COMMENT = '服务器任务关联表' ROW_FORMAT = Dynamic";
            $this->db()->execute($sql);
        }
    }
}
